import { Request } from "express";
import literatureSql from "@src/sql/literatureSql";
import Constant from "@src/util/constant";
import dictSql from "@src/sql/dictSql";
import articleSql from "@src/sql/articleSql";
import { getMeta } from "@src/util/util";

const add = async (req: Request) => {
  const { category_id, name, cover_id } = req.body;
  // 是否存在分类
  if (!(await dictSql.isCategoryId(category_id))) {
    return Constant.CATEGORY_ERROR;
  }
  // 名字是否重复
  if (await articleSql.isArticleName(name)) {
    return Constant.ADD_ERROR;
  }
  // 附件是否存在
  if (!(await literatureSql.isFileId(cover_id))) {
    return Constant.FILE_ID_ERROR;
  }
  return await articleSql.add(req);
};

// 更新文章
const update = async (req: Request) => {
  const { id } = req.params;
  // 文章数据是否存在
  if (!(await articleSql.isArticleId(id))) {
    return Constant.ARTICLE_NOT_ERROR;
  }
  const { category_id, name, cover_id } = req.body;
  // 是否存在分类
  if (!(await dictSql.isCategoryId(category_id))) {
    return Constant.CATEGORY_ERROR;
  }
  // 名字是否重复
  if (await articleSql.isArticleName(name)) {
    return Constant.ADD_ERROR;
  }
  // 附件是否存在
  if (!(await literatureSql.isFileId(cover_id))) {
    return Constant.FILE_ID_ERROR;
  }
  await articleSql.update(req);
  return Constant.DEFAULT_SUCCESS;
};

// 文章列表
const list = async (page: number, size: number, filters: any) => {
  const offset = (page - 1) * size;
  const { count, rows, dictData } = await articleSql.list(offset, size, filters);
  const meta = getMeta(count, page, size);
  return {
    ...Constant.DEFAULT_SUCCESS,
    meta,
    data: rows,
    type_id: dictData.type_id,
  };
};

// 更新首页推荐
const updateRecommend = async (id: string, recommend: number) => {
  // 是否存在
  if (!(await articleSql.isArticleId(id))) {
    return Constant.ARTICLE_NOT_ERROR;
  }
  return await articleSql.updateRecommend(id, recommend);
};



// 更新上架
const updateGrounding = async (id: string, grounding: number) => {
  if (!(await articleSql.isArticleId(id))) {
    return Constant.ARTICLE_NOT_ERROR;
  }
  return await articleSql.updateGrounding(id, grounding);
};

// 文章详情
const detail = async (id: string) => {
  if (!(await articleSql.isArticleId(id))) {
    return Constant.ARTICLE_NOT_ERROR;
  }
  return await articleSql.detail(id);
};

// 前台
const frontList = async (page: number, size: number, id: string, filters: any) => {
  const offset = (page - 1) * size;
  const { count, rows } = await articleSql.frontList(offset, size, id, filters);
  const meta = getMeta(count, page, size);
  return {
    ...Constant.DEFAULT_SUCCESS,
    meta,
    data: rows,
  };
};
export default {
  add,
  update,
  list,
  updateRecommend,
  updateGrounding,
  detail,
  frontList,
};
